<template>
  <div>
    <!-- 考核单维护 -- 车厂-->
    <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="110" @filterChange="changeHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :fetchapi="fetchapi"
      :datakey="'records'"
      :onColumnsChange="(columns) => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :is-select-column="true"
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" icon="el-icon-check" :click="qiyong.bind()">批量提交</multiuse-button>
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">新增</multiuse-button>
        <multiuse-button size="small" type="primary" :click="downloadTemplate.bind()">下载模板</multiuse-button>
        <multiuse-button size="small" icon="el-icon-upload" @click="showImportFun()">导入</multiuse-button>
        <!--        <multiuse-button size="small" type="primary"  @click="exportFileBtn()">导出</multiuse-button>-->
      </template>
    </FilterTable>
    <Drawer :visible.sync="visible" :title="'考核单编辑'" destroyOnClose width="60%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <xiangqing @close="close" @save="save" :rowData="rowData"></xiangqing>
    </Drawer>
    <BaseDialog :visible.sync="selectDelearFlag" :title="'经销商选择'" width="850px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <DealerList @close="Delearclose" @save="Delearsave"></DealerList>
    </BaseDialog>
    <Drawer :visible.sync="visibleAdd" :title="'考核单新增'" destroyOnClose width="60%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <AddForm @close="closeAdd" @save="saveAdd"></AddForm>
    </Drawer>
    <BaseDialog :visible.sync="showImport" :closable="false" icon="el-icon-upload" title="导入" width="800px" destroyOnClose :containerStyle="{ height: 'calc(100% - 120px)', overflow: 'auto', paddingBottom: '60px' }">
      <importExcel @close="showImport = false" @importclose="editsave1()" url="/api/cms_claimfac/rPAssess/importExcel"/>
    </BaseDialog>
  </div>
</template>
<script>
import xiangqing from './xiangqing.vue';
// import importKaoHeDanWeiHu from './importKaoHeDanWeiHu.vue';
import importExcel from '@/pages/claimDemage/tools/importExcel.vue';
import selectDelearPage from './selectDelearPage.vue';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import { exportExcelFile } from '@/utils/index';
import AddForm from './AddForm.vue';
import { getListByPage, getPartType, deleteOne, downloadModel, getListForExport, editSave, quyrPAssess,piliangtijiao} from '@/api/claim/factory/CheckSheetMaintain';
import {  getAppId } from '@/assets/js/auth';
import { dictionary } from '@/utils/dictMixin';
import moment from "moment";
export default {
   mixins: [dictionary],
  components: {
    xiangqing,
    selectDelearPage,
    DealerList,
    // importKaoHeDanWeiHu,
    AddForm,
    importExcel
  },
  data() {
    return {
      dataList: [],
      rowData: {},
      editRow: {},
      visible: false,
      selectDelearFlag: false,
      visibleDrawer: false,
      collapse: true,
      infoId: null,
      topFilterInit: this.topFilterInitFun(),
      flterValue: {}, //参数
      fetchapi: getListByPage,
      columns: this.creatHeader(),
      fetchParams: {
        techStatusStrs: '',
        xhrAbort: true,
      }, //ipa 接口
      selectedRows: [], //选中经销商
      dialogTitle: '选择车辆',
      visibleAdd: false,
      showImport: false,
    };
  },
  created() {
    if (getAppId() == 'arcfox') {
      this.topFilterInit.find(x => x.fieldName == 'assessClassify').itemList =this.createDictList('5543',[55431001])
        this.topFilterInit.find(x => x.fieldName == 'assessStatus').itemList =this.createDictList('5545',[55451002,55451004,55451005,55451006])
        this.fetchParams.techStatusStrs='55451001,55451003'
    }else{
      this.topFilterInit.find(x => x.fieldName == 'assessClassify').itemList =this.createDictList('5543')
        this.topFilterInit.find(x => x.fieldName == 'assessStatus').itemList =this.createDictList('5545',[55451005,55451006])
        this.fetchParams.techStatusStrs='55451002,55451001,55451003,55451004'

    }
    this.fetchParams.beginCreatedAt = moment().startOf('week').format('YYYY-MM-DD HH:mm:ss');
    this.fetchParams.endCreatedAt = moment().endOf('week').format('YYYY-MM-DD HH:mm:ss');
    this.chuqi();
    this.chuqi1();
    this.chuqi2();
  },
  methods: {
    editsave1() {
      this.showImport = false;
      this.fetchParams = { ...this.fetchParams };
    },
    // Excel更新导入
    showImportFun() {
      this.showImport = true;
    },
    //下载模板
    downloadTemplate() {
      this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        downloadModel().then((res) => {
          console.log(res);
          exportExcelFile(res.data, '考核单维护导入模板');
        });
      });
    },
    // 导出
    exportFileBtn() {
      let beginSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[0];
      let endSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[1];
      if(!beginSubmitDate) {
        this.$notify.warning({ title: '提示信息', message: '考核开始日期不可为空！' });
        return
      }
      if(!endSubmitDate) {
        this.$notify.warning({ title: '提示信息', message: '考核结束日期不可为空！' });
        return
      }
      if(getAppId() == 'arcfox') {
        if (moment(moment(endSubmitDate).format('YYYY-MM-DD')).diff(moment(beginSubmitDate), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '考核日期跨度不可超过十二个月！' });
          return
        }
      } else {
        if (moment(moment(endSubmitDate).format('YYYY-MM-DD')).diff(moment(beginSubmitDate), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '考核日期跨度不可超过十二个月！' });
          return
        }
      }
      let obj = Object.assign({}, this.fetchParams, {xhrAbort: false});
      obj.beginCreatedAt = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[0];
      obj.endCreatedAt = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[1];
      getListForExport(obj).then((res) => {
        exportExcelFile(res.data, '考核单信息');
      });
    },
    //批量提交
    async qiyong() {
      if (this.selectedRows.length > 0) {
        let str = '';
        this.selectedRows.map(x => {
          str += x.assessId + ',';
        });
        console.log(str);
        const res = await piliangtijiao({ ids: str,assessStatus: '55451002' });
        this.fetchParams = { ...this.fetchParams };
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请勾选后再进行提交！' });
      }
    },
    // 删除
    async delFun(val) {
      this.$confirm('确定作废吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          this.res = await deleteOne(val.assessId);
          if (this.res.resultCode != 200) {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '作废失败!' });
          } else {
            this.$notify.success({ title: '提示信息', message: '作废成功!' });
            this.fetchParams = { ...this.fetchParams };
          }
        })
    }, // 提交
    async submitFun(val) {
      this.$confirm('确定提交吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let res1 = await quyrPAssess(val.assessId);
          this.editRow = res1.data;
          this.editRow.assessStatus = 55451002;
          let res = await editSave(this.editRow);
          if (res.resultCode != 200) {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '提交失败!' });
          } else {
            this.$notify.success({ title: '提示信息', message: '提交成功!' });
            this.fetchParams = { ...this.fetchParams };
          }
        })
    },
    //撤销
      async undoFun(val) {
      this.$confirm('确定撤销吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
    
        .then(async () => {
          let res1 = await quyrPAssess(val.assessId);
          this.editRow = res1.data;
          this.editRow.assessStatus = 55451001;
          let res = await editSave(this.editRow);
          if (res.resultCode != 200) {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '撤销失败!' });
          } else {
            this.$notify.success({ title: '提示信息', message: '撤销成功!' });
            this.fetchParams = { ...this.fetchParams };
          }
        })
    },
    //考核类型
    async chuqi() {
      // const res = await getPartType({ type: 5541 });
      // if (res.resultCode == 200) {
      //   this.topFilterInit.find((x) => x.fieldName == 'assessType').initialValue = '';
      //   this.topFilterInit.find((x) => x.fieldName == 'assessType').itemList = res.data.map((y) => ({
      //     text: y.codeCnDesc,
      //     value: y.codeId,
      //   }));
      // }
    },
    //考核单状态
    async chuqi1() {
      // const res = await getPartType({ type: 5545 });
      // if (res.resultCode == 200) {
      //   delete res.data[1];
      //   delete res.data[3];
      //   delete res.data[4];
      //   delete res.data[5];
      //   this.topFilterInit.find((x) => x.fieldName == 'assessStatus').initialValue = '';
      //   this.topFilterInit.find((x) => x.fieldName == 'assessStatus').itemList = res.data.map((y) => ({
      //     text: y.codeCnDesc,
      //     value: y.codeId,
      //   }));
      // }
    },
    //考核分类
    async chuqi2() {
      // const res = await getPartType({ type: 5543 });
      // if(getAppId()=='arcfox') {
      //   delete res.data[0]
      // }
      // if (res.resultCode == 200) {
      //   this.topFilterInit.find((x) => x.fieldName == 'assessClassify').initialValue = '';
      //   this.topFilterInit.find((x) => x.fieldName == 'assessClassify').itemList = res.data.map((y) => ({
      //     text: y.codeCnDesc,
      //     value: y.codeId,
      //   }));
      // }
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    close() {
      this.visible = false;
    },
    chooseOrderNo(val) {
      this.visible = true;
      this.rowData = val;
    },
    save() {
      this.visible = false;
      this.fetchParams = { ...this.fetchParams };
    },
    add() {
      this.visibleAdd = true;
    },
    closeAdd() {
      this.visibleAdd = false;
    },
    saveAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    //经销商选择页面
    SelectDelear() {
      this.selectDelearFlag = true;
    }, //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    //保存
    Delearsave(obj) {
      this.topFilterInit.map((x) => {
        if ('dealerCode' == x.fieldName) {
          x.initialValue = obj[0].dealerCode; //维修工单号返显
        }
      });
      this.selectDelearFlag = false;
    },
    //搜索获取数据
    changeHandle(val) {
      if(!val.beginCreatedAt) {
        this.$notify.warning({ title: '提示信息', message: '考核开始日期不可为空！' });
        return
      }
      if(!val.endCreatedAt) {
        this.$notify.warning({ title: '提示信息', message: '考核结束日期不可为空！' });
        return
      }
      if(getAppId() == 'arcfox') {
        if (moment(moment(val.endCreatedAt).format('YYYY-MM-DD')).diff(moment(val.beginCreatedAt), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '考核日期跨度不可超过十二个月！' });
          return
        }
      } else {
        if (moment(moment(val.endCreatedAt).format('YYYY-MM-DD')).diff(moment(val.beginCreatedAt), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '考核日期跨度不可超过十二个月！' });
          return
        }
      }
      this.fetchParams = Object.assign({}, this.fetchParams, val,{xhrAbort: false});
      // this.SELECT();
    },
    //搜索数据
    topFilterInitFun() {
      return [
        { type: 'INPUT', label: '考核单号', fieldName: 'assessNo', placeholder: '请输入考核单号...', initialValue: '' },
        { type: 'SELECT', label: '考核类型', fieldName: 'assessType', placeholder: '请选择考核类型...', initialValue: '', itemList: this.createDictList('5541') },
        { type: 'SELECT', label: '考核单状态', fieldName: 'assessStatus', placeholder: '请选择考核单状态...', initialValue: '', itemList: []},
        {
          type: 'RANGE_DATE',
          label: '考核日期',
          fieldName: 'beginCreatedAt|endCreatedAt',
          placeholder: '请输入',
          initialValue: [
            moment()
              .startOf('week')
              .format('YYYY-MM-DD HH:mm:ss'),
            moment()
              .endOf('week')
              .format('YYYY-MM-DD HH:mm:ss')
          ],
          rules: [{ required: true, message: '请选择日期', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请输入经销商代码...',
          initialValue: '',
          unitRender: (p) => {
            return (
              <div>
                <multiuse-button icon="el-icon-search" onClick={() => this.SelectDelear()} />
              </div>
            );
          },
        },
        // { type: 'INPUT', label: '经销商名称', fieldName: 'dealerName', placeholder: '请输入经销商名称...', initialValue: '' },
        {
          type: 'SELECT',
          label: '考核分类',
          fieldName: 'assessClassify',
          placeholder: '请选择考核分类...',
          initialValue: '',
          itemList: [],
        },
      ];
    },
    //     <multiuse-button size="mini" type="text" disabled={((props.row.assessStatus == '55451002') || (props.row.assessStatus =='55451003') || (props.row.assessStatus =='55451004') || (props.row.assessStatus =='55451005'))? true: false }  onClick={() => this.delFun(props.row)}>
    // 删除 先留着以后用
    // </multiuse-button>
    //table表头和数据源
    // 55451001  录入   55451002 已提交   55451003 驳回   55451004 通过  55451005  作废
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          fixed: 'left',
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 150,
          render: (props, h) => {
            if(getAppId()=='beijing'){
            return (
              <div style="text-align:center">
                <multiuse-button
                  size="mini"
                  type="text"
                  disabled={props.row.assessStatus == '55451002' || props.row.assessStatus == '55451004' || props.row.assessStatus == '55451005' ? true : false}
                  onClick={() => this.chooseOrderNo(props.row)}
                >
                  编辑
                </multiuse-button>
                <multiuse-button
                  size="mini"
                  type="text"
                  disabled={props.row.assessStatus == '55451001' || props.row.assessStatus == '55451003' ? false : true}
                  onClick={() => this.submitFun(props.row)}
                >
                  提交
                </multiuse-button>
                <multiuse-button
                  size="mini"
                  type="text"
                  disabled={(props.row.assessStatus == '55451004' ) || props.row.assessStatus == '55451002' ? false : true}
                  onClick={() => this.undoFun(props.row)}
                >
                  撤销
                </multiuse-button>
                <multiuse-button size="mini" type="text" disabled={props.row.assessStatus == '55451001' || props.row.assessStatus == '55451003' ? false : true} onClick={() => this.delFun(props.row)}>
                  作废
                </multiuse-button>
              </div>
            );
            }else{
              return (
              <div style="text-align:center">
                <multiuse-button
                  size="mini"
                  type="text"
                  disabled={props.row.assessStatus == '55451002' || props.row.assessStatus == '55451004' || props.row.assessStatus == '55451005' ? true : false}
                  onClick={() => this.chooseOrderNo(props.row)}
                >
                  编辑
                </multiuse-button>
                <multiuse-button
                  size="mini"
                  type="text"
                  disabled={props.row.assessStatus == '55451001' || props.row.assessStatus == '55451003' ? false : true}
                  onClick={() => this.submitFun(props.row)}
                >
                  提交
                </multiuse-button>
                <multiuse-button size="mini" type="text" disabled={props.row.assessStatus == '55451001' || props.row.assessStatus == '55451003' ? false : true} onClick={() => this.delFun(props.row)}>
                  作废
                </multiuse-button>
              </div>
            );
            }
          },
        },
        { title: '考核单状态', dataIndex: 'statusStr', sorter: true },
        { title: '考核单号', dataIndex: 'assessNo', sorter: true },
        { title: '考核分类', dataIndex: 'assessClassifyStr', sorter: true },
        { title: '考核类型', dataIndex: 'assessTypeStr', sorter: true },
        { title: '经销商代码', dataIndex: 'dealerCode', sorter: true },
        { title: '经销商名称', dataIndex: 'dealerName', sorter: true },
        { title: '考核金额', dataIndex: 'assessAmount', sorter: true },
        { title: '考核原因', dataIndex: 'assessReason', sorter: true },
        { title: '备注', dataIndex: 'assessRemarks', sorter: true },
        { title: '考核日期', dataIndex: 'assessDate', sorter: true, dateFormat: 'yyyy-MM-dd' },
        { title: '考核人', dataIndex: 'assessByStr', sorter: true },
        // { title: '主键', dataIndex: 'assessId', sorter: true, hidden: true },
        // { title: '主键', dataIndex: 'assessStatus', sorter: true, hidden: true },
      ];
    },
  },
};
</script>

<style lang="less" scoped></style>
